package com.cxb;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.cxb.view.SwitchButton;
import com.cxb.view.SwitchButton.OnSwitchListener;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class BlueToothManagerActivity extends BaseActivity {
	private BlueToothStateBroadcastRecever btsBroadcastRecever;
	private BluetoothAdapter mAdapter;
	private SwitchButton wiperSwitch;
	private ListView lv_device;
	private List<BluetoothDevice> bluetoothDevice_list;
	private BlueToothViewAdapter mBlueToothViewAdapter;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bluetooth_manager);
		init();
	}

	private void init() {
		btsBroadcastRecever = new BlueToothStateBroadcastRecever();
		IntentFilter filter = new IntentFilter();
		mAdapter = BluetoothAdapter.getDefaultAdapter();
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
		filter.addAction(BluetoothDevice.ACTION_FOUND);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		this.registerReceiver(btsBroadcastRecever, filter);
		
		
		lv_device = (ListView)findViewById(R.id.lv_device);
		wiperSwitch = (SwitchButton) findViewById(R.id.wiperSwitch);
		wiperSwitch.setOn(isOpen());
		wiperSwitch.setOnSwitchListener(new OnSwitchListener() {
			
			@Override
			public void onSwitch(boolean isOn, View view) {
				if(isOn)
					openBlueTooth();
				else
					closeBlueTooth();
			}
		});
		mBlueToothViewAdapter = new BlueToothViewAdapter(this, bluetoothDevice_list);
		lv_device.setAdapter(mBlueToothViewAdapter);
		
		Set<BluetoothDevice> devices = mAdapter.getBondedDevices();
		if(devices.size()>0)    
			for(Iterator iterator = devices.iterator();iterator.hasNext();addDevice((BluetoothDevice)iterator.next()))
				;
	}

	private void openBlueTooth() {
		if (mAdapter != null)
		{
			mAdapter.enable();
			new Handler().postDelayed(new Runnable() {
				
				@Override
				public void run() {
					mAdapter.startDiscovery();
				}
			}, 3000);
			
		}
	}
	
	private void closeBlueTooth() {
		if (mAdapter != null)
		{
			mAdapter.disable();
			mAdapter.cancelDiscovery();
		}
			
		bluetoothDevice_list = null;
	}

	private boolean isOpen() {
		return mAdapter == null ? false : mAdapter.isEnabled();
	}

	private void startBlueToothService() {

	}

	private void startBlueToothClient() {

	}

	private void stopService() {

	} 

	private void stopClient() {

	}
	
	private void addDevice(BluetoothDevice mBluetoothDevice)
	{
		if(bluetoothDevice_list == null)
			bluetoothDevice_list = new ArrayList<BluetoothDevice>();
		bluetoothDevice_list.add(mBluetoothDevice);
		Log.d("pumkid", "bluetoothDevice_list" + bluetoothDevice_list.size());
		if(mBlueToothViewAdapter != null)
		{
			mBlueToothViewAdapter.setBluetoothDevice_list(bluetoothDevice_list);
			mBlueToothViewAdapter.notifyDataSetChanged();
		}
	}
	
	class BlueToothStateBroadcastRecever extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {

	        String action = intent.getAction();  
	        if (BluetoothDevice.ACTION_FOUND.equals(action)) {  
	        	
	            BluetoothDevice device = intent  
	                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
	            Log.d("pumkid", "BluetoothDevice"+device.getName());
	            addDevice(device);
	            if (device.getBondState() != BluetoothDevice.BOND_BONDED) {  
	            	
	            }  
	        }  
	        
	        if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {  
	        	Log.d("pumkid", "ACTION_DISCOVERY_STARTED");
	        }  
	        
	        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED  
	                .equals(action)) {  
	        	Log.d("pumkid", "ACTION_DISCOVERY_FINISHED");
	        }  
		}
	}
	
	class BlueToothViewAdapter extends BaseAdapter{
		private List<BluetoothDevice> bluetoothDevice_list;
		private Context context;
		
		
		public BlueToothViewAdapter(Context context, List<BluetoothDevice> bluetoothDevice_list)
		{
			this.context = context;
			this.bluetoothDevice_list = bluetoothDevice_list;
		}
		
		public void setBluetoothDevice_list(List<BluetoothDevice> bluetoothDevice_list)
		{
			this.bluetoothDevice_list = bluetoothDevice_list;
		}
		
		@Override
		public int getCount() {
			return bluetoothDevice_list == null ? 0 : bluetoothDevice_list.size();
		}

		@Override
		public Object getItem(int index) {
			return bluetoothDevice_list == null ? null : bluetoothDevice_list.get(index);
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int posistion, View view, ViewGroup parent) {
			View contentview = view;
			if(view == null)
				contentview = LayoutInflater.from(context).inflate(R.layout.bluetooth_item, null);
			Log.d("pumkid", "getView");
			BluetoothDevice mbluetoothDevice = bluetoothDevice_list.get(posistion);
			TextView tv_bluetoothname = (TextView)contentview.findViewById(R.id.tv_bluetoothname);
			tv_bluetoothname.setText(mbluetoothDevice.getName());
			return contentview;
		}
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(btsBroadcastRecever != null)
				unregisterReceiver(btsBroadcastRecever);
	}
}
